﻿using System.Data;
using System.Net.Sockets;
using System.Security.Cryptography;

namespace Basic.Base.UtilityTools;

public class CommonTool
{
    /// <summary>
    /// 根据以逗号分隔的字符串转换为集合
    /// </summary>
    /// <param name="strArr"></param>
    /// <returns></returns>
    public static List<int> GetStrList(string strArr)
    {
        if (string.IsNullOrWhiteSpace(strArr))
            return new List<int>();
        else
            return strArr.Split(',').Select(x => int.Parse(x)).ToList();
    }

    public static List<string> GetStrToList(string strArr)
    {
        if (string.IsNullOrWhiteSpace(strArr))
            return new List<string>();
        else
            return strArr.Split(',').Select(x => x).ToList();
    }

    /// <summary>
    /// MD5加密。32位小写
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string MD5Encrypt(string str)
    {
        if (string.IsNullOrWhiteSpace(str))
            return string.Empty;

        //MD5 md5 = MD5.Create();
        //byte[] data = Encoding.Default.GetBytes(str);
        //byte[] md5data = md5.ComputeHash(data);
        //md5.Clear();
        //var md5str = "";
        //for (int i = 0; i < md5data.Length; i++)
        //{
        //    md5str += md5data[i].ToString("x").PadLeft(2, '0');
        //}
        //return md5str;

        using (MD5 md5 = MD5.Create())
        {
            byte[] msgBuffer = Encoding.UTF8.GetBytes(str);

            byte[] md5Buffer = md5.ComputeHash(msgBuffer);
            md5.Clear();
            StringBuilder sbMd5 = new StringBuilder();
            for (int i = 0; i < md5Buffer.Length; i++)
            {
                sbMd5.Append(md5Buffer[i].ToString("x2")); //小写
            }
            return sbMd5.ToString();
        }
    }

    private static string? _locaIP;
    public static string GetLocalIP()
    {
        if (_locaIP == null)
        {
            var entry = Dns.GetHostEntry(Dns.GetHostName());
            var list = entry?.AddressList;
            _locaIP = list?.Where(s => s.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault()?.ToString();
        }
        return _locaIP;
    }

}